//
//  ZCMusicListViewController.m
//  VoiceMusic
//
//  Created by dllo on 15/10/16.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCMusicListViewController.h"
#import "ZCBaseView.h"
#import "ZCAFNetWork.h"
#import "ZCMusicListModel.h"
#import "ZCHotCollectionViewCell.h"
#import "ZCAllSortedViewController.h"
#import "ZCDetaileListViewController.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ZCMusicListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *hotCollectionView;
@property (nonatomic, strong) UICollectionView *newlyCollectionView;
@property (nonatomic, strong) NSMutableArray *hotArr;
@property (nonatomic, strong) NSMutableArray *newlyArr;
@property (nonatomic, strong) ZCBaseView *headView;
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, assign) NSInteger hotCount;
@property (nonatomic, assign) NSInteger newlyCount;
@property (nonatomic, strong) UIButton *hotButton;
@property (nonatomic, strong) UIButton *newlyButton;
@property (nonatomic, strong) UIButton *allButton;
@property (nonatomic, copy) NSString *str;
@property (nonatomic, copy) NSString *newly;
@property (nonatomic, copy) NSString *titleStr;
@end

@implementation ZCMusicListViewController

#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hotArr = [NSMutableArray array];
        self.newlyArr = [NSMutableArray array];
        self.str = @"最热";
        self.newly = @"最新";
    }
    return self;
}

#pragma mark 代理置空
- (void)dealloc
{
    _hotCollectionView.delegate = nil;
    _hotCollectionView.dataSource = nil;
    _newlyCollectionView.dataSource = nil;
    _newlyCollectionView.delegate = nil;
}
#pragma mark 返回
- (void)returnClick:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"750365_105833058_2"]];
    //返回键
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.headView = [[ZCBaseView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    [self.view addSubview:self.headView];
    // count初始值
    self.hotCount = 2;
    self.newlyCount = 2;
    // 最热最新按钮
    self.hotButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.hotButton.frame = CGRectMake(WIDTH - 120 , 0, 60, 40);
    [self.view addSubview:self.hotButton];
    [self.hotButton setTitle:@"最热" forState:UIControlStateNormal];
    [self.hotButton addTarget:self action:@selector(hotClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.newlyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.newlyButton.frame = CGRectMake(WIDTH - 60 , 0, 60, 40);
    [self.view addSubview:self.newlyButton];
    [self.newlyButton setTitle:@"最新" forState:UIControlStateNormal];
    [self.newlyButton addTarget:self action:@selector(newlyClick:) forControlEvents:UIControlEventTouchUpInside];
    // 全部按钮
    self.allButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.allButton.frame = CGRectMake(10, 0, 60, 40);
    [self.view addSubview:self.allButton];
    [self.allButton setTitle:@"全部" forState:UIControlStateNormal];
    [self.allButton addTarget:self action:@selector(allClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self createHotCollectionView];
    [self createHotCollectionViewData];
    [self createNewlyCollectionViewData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(not:) name:@"name" object:nil];
    
}


#pragma mark 接收传值信息.
-(void)not:(NSNotification *)nott {
    self.titleStr = nott.userInfo[@"n"];
    self.str = [NSString stringWithFormat:@"最热|%@",nott.userInfo[@"n"]];
    self.newly = [NSString stringWithFormat:@"最新|%@",nott.userInfo[@"n"]];
    [self createHotCollectionViewData];
    [self createNewlyCollectionViewData];
    self.newlyCollectionView.contentOffset = CGPointMake(0, 0);
    self.hotCollectionView.contentOffset = CGPointMake(0, 0);
}

#pragma mark 点击的执行方法
- (void)hotClick:(UIButton *)button
{
    [self.newlyCollectionView removeFromSuperview];
    [self.hotCollectionView removeFromSuperview];
    [self createHotCollectionView];
    if (self.hotArr.count != 0) {
        [self createHotCollectionViewData];
    }
}
- (void)newlyClick:(UIButton *)button
{
    [self.hotCollectionView removeFromSuperview];
    [self.newlyCollectionView removeFromSuperview];
    [self createNewlyCollectionView];
    if (self.newlyArr.count != 0) {
        [self createNewlyCollectionViewData];
    }
}

#pragma mark 全部按钮实现
- (void)allClick:(UIButton *)button
{
    ZCAllSortedViewController *allSortedVC = [[ZCAllSortedViewController alloc] init];
    [self.navigationController pushViewController:allSortedVC animated:YES];
}

#pragma mark 创建最热视图
- (void)createHotCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH / 2, WIDTH / 2);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.hotCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, HEIGHT - 40 - 64 - 49) collectionViewLayout:flowLayout];
    self.hotCollectionView.backgroundColor = [UIColor clearColor];
    self.hotCollectionView.delegate = self;
    self.hotCollectionView.dataSource = self;
    self.hotCollectionView.emptyDataSetDelegate = self;
    self.hotCollectionView.emptyDataSetSource = self;
    [self.view addSubview:self.hotCollectionView];
    [self.hotCollectionView registerClass:[ZCHotCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    

}

#pragma mark 创建最热数据
- (void)createHotCollectionViewData
{
    NSString *front = @"http://so.ard.iyyin.com/s/songlist?s=s200&size=10&hid=6125550060252570&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&q=tag%3A";
    NSString *back = @"&net=2&app=ttpod&v=v8.1.0.2015071519&alf=alf700159&tid=0&uid=863583022034533&f=f168&page=1&imsi=460026046186283";
    NSString *changeStr = [self.str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",front,changeStr,back];
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        self.hotArr = [ZCMusicListModel baseModelByArr:dic[@"data"]];
        //下拉刷新
        self.hotCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self loadNewData];
        }];
        //上拉加载
        self.hotCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self loadMoreData];
        }];
        [self.hotCollectionView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"error == %@",error);
    }];
}

#pragma mark 创建最新视图
- (void)createNewlyCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH / 2, WIDTH / 2);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.newlyCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, HEIGHT - 40 - 64 - 49) collectionViewLayout:flowLayout];
    self.newlyCollectionView.backgroundColor = [UIColor clearColor];
    self.newlyCollectionView.delegate = self;
    self.newlyCollectionView.dataSource = self;
    self.newlyCollectionView.emptyDataSetDelegate = self;
    self.newlyCollectionView.emptyDataSetSource = self;
    [self.view addSubview:self.newlyCollectionView];
    [self.newlyCollectionView registerClass:[ZCHotCollectionViewCell class] forCellWithReuseIdentifier:@"Reuse"];
}

#pragma mark 创建最新数据
- (void)createNewlyCollectionViewData
{
    NSString *front = @"http://so.ard.iyyin.com/s/songlist?s=s200&size=10&hid=6125550060252570&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&q=tag%3A";
    NSString *back = @"&net=2&app=ttpod&v=v8.1.0.2015071519&alf=alf700159&tid=0&uid=863583022034533&f=f168&page=1&imsi=460026046186283";
    
    NSString *changeStr = [self.newly stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",front,changeStr,back];
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        self.newlyArr = [ZCMusicListModel baseModelByArr:dic[@"data"]];
        //下拉刷新
        self.newlyCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self loadNewNewlyData];
        }];
        //上拉加载
        self.newlyCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self loadMoreNewlyData];
        }];
        [self.newlyCollectionView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"error == %@",error);
    }];
}

#pragma mark collectionView实现方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.hotCollectionView) {
        return self.hotArr.count;
    }else if (collectionView == self.newlyCollectionView)
    {
        return self.newlyArr.count;
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.hotCollectionView) {
        ZCHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        ZCMusicListModel *musicModel = self.hotArr[indexPath.row];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:musicModel.pic_url]placeholderImage:[UIImage imageNamed:@"3187"]];
        cell.backgroundColor = [UIColor clearColor];
        cell.titleLabel.text = musicModel.title;
        return cell;
    }else if(collectionView == self.newlyCollectionView)
    {
        ZCHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Reuse" forIndexPath:indexPath];
        ZCMusicListModel *musicModel = self.newlyArr[indexPath.row];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:musicModel.pic_url]placeholderImage:[UIImage imageNamed:@"3187"]];
        cell.backgroundColor = [UIColor clearColor];
        cell.titleLabel.text = musicModel.title;
        return cell;
    }
    return nil;
}

#pragma mark hot数据的加载刷新
#pragma mark 下拉刷新
- (void)loadNewData
{
    NSString *front = @"http://so.ard.iyyin.com/s/songlist?s=s200&size=10&hid=6125550060252570&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&q=tag%3A";
    NSString *back = @"&net=2&app=ttpod&v=v8.1.0.2015071519&alf=alf700159&tid=0&uid=863583022034533&f=f168&page=1&imsi=460026046186283";
    
    NSString *changeStr = [self.str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",front,changeStr,back];

    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        self.hotArr = [ZCMusicListModel baseModelByArr:dic[@"data"]];
        [self.hotCollectionView reloadData];
        // 加载数据之后结束
        [self.hotCollectionView.header endRefreshing];
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 上拉加载
- (void)loadMoreData
{
    NSString *front = @"http://so.ard.iyyin.com/s/songlist?s=s200&size=10&hid=6125550060252570&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&q=tag%3A";
    NSString *back = @"&net=2&app=ttpod&v=v8.1.0.2015071519&alf=alf700159&tid=0&uid=863583022034533&f=f168&page=";
    NSString *changeStr = [self.str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@%@%ld",front,changeStr,back,self.hotCount];
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *arr = [NSMutableArray array];
        [arr removeAllObjects];
        arr = [ZCMusicListModel baseModelByArr:dic[@"data"]];
        [self.hotArr addObjectsFromArray:arr];
        [self.hotCollectionView reloadData];
        self.hotCount = self.hotCount + 1;
    } failure:^(NSError *error) {
        NSLog(@"error = %@",error);
    }];
    [self.hotCollectionView.footer endRefreshing];
}

#pragma mark 最新数据的加载
#pragma mark 下拉刷新
- (void)loadNewNewlyData
{
    NSString *front = @"http://so.ard.iyyin.com/s/songlist?s=s200&size=10&hid=6125550060252570&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&q=tag%3A";
    NSString *back = @"&net=2&app=ttpod&v=v8.1.0.2015071519&alf=alf700159&tid=0&uid=863583022034533&f=f168&page=1&imsi=460026046186283";
    
    NSString *changeStr = [self.newly stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@%@",front,changeStr,back];
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSDictionary *dic = result;
        self.newlyArr = [ZCMusicListModel baseModelByArr:dic[@"data"]];
        [self.newlyCollectionView reloadData];
        // 加载数据之后结束
        [self.newlyCollectionView.header endRefreshing];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 上拉加载
- (void)loadMoreNewlyData
{
    NSString *front = @"http://so.ard.iyyin.com/s/songlist?s=s200&size=10&hid=6125550060252570&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&q=tag%3A";
    NSString *back = @"&net=2&app=ttpod&v=v8.1.0.2015071519&alf=alf700159&tid=0&uid=863583022034533&f=f168&page=";
    
    NSString *changeStr = [self.newly stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = [NSString stringWithFormat:@"%@%@%@%ld",front,changeStr,back,self.newlyCount];
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *arr = [NSMutableArray array];
        [arr removeAllObjects];
        arr = [ZCMusicListModel baseModelByArr:dic[@"data"]];
        [self.newlyArr addObjectsFromArray:arr];
        [self.newlyCollectionView reloadData];
        self.newlyCount = self.newlyCount + 1;
    } failure:^(NSError *error) {
        NSLog(@"error = %@",error);
    }];
    [self.newlyCollectionView.footer endRefreshing];
}
#pragma mark 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.hotCollectionView) {
        ZCDetaileListViewController *detailListVC = [[ZCDetaileListViewController alloc] init];
        ZCMusicListModel *musicModel = self.hotArr[indexPath.row];
        detailListVC.myId = musicModel._id;
        [self.navigationController pushViewController:detailListVC animated:YES];
    }else if (collectionView == self.newlyCollectionView)
    {
        ZCDetaileListViewController *detailListVC = [[ZCDetaileListViewController alloc] init];
        ZCMusicListModel *musicModel = self.newlyArr[indexPath.row];
        detailListVC.myId = musicModel._id;
        [self.navigationController pushViewController:detailListVC animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
